package com.unitd.base.module.consumer.controller;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unitd.base.frame.enums.OrderStateEnum;
import com.unitd.base.frame.plugin.module.dto.ResponseUtils;
import com.unitd.base.frame.util.BeanUtils;
import com.unitd.base.module.consumer.comm.annotation.IgnoreAuth;
import com.unitd.base.module.consumer.comm.annotation.LoginUser;
import com.unitd.base.module.consumer.comm.controller.ApiBaseAction;
import com.unitd.base.module.master.pojo.dto.UserVO;
import com.unitd.base.module.shoe.pojo.dto.GoodsVO;
import com.unitd.base.module.shoe.pojo.po.CustomerOrderItemPO;
import com.unitd.base.module.shoe.pojo.po.CustomerOrderPO;
import com.unitd.base.module.shoe.service.GoodsService;
import com.unitd.base.module.shoe.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 个人中心管理前端控制器类
 *
 * @author hudan
 * @version 1.0
 * @filename ApiClientCenterController.java
 * @copyright www.pactera.com
 * @date 2020-08-14
 */
@Api(tags = "个人中心管理")
@RestController
@RequestMapping("/api/clientCenter")
public class ApiClientCenterController extends ApiBaseAction {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    /**
     * 商品信息列表
     */
    @ApiOperation(value = "商品信息列表", response = Map.class)
    @PostMapping("cGoodsShelvesList")
    public Object cGoodsShelvesList(@LoginUser UserVO loginUser) {

        List<GoodsVO> vos = goodsService.selectByBean(loginUser.getCompanyDatasource().getDbName(), Maps.newHashMap());
        return ResponseUtils.toResponsSuccess(vos);
    }

    /**
     * 客户订单确认列表
     */
    @ApiOperation(value = "客户订单确认列表", response = Map.class)
    @IgnoreAuth
    @PostMapping("cOrderConfirmList")
    public Object cOrderConfirmList(@RequestParam Map<String, Object> params) {
        List<HashMap<String, Object>> cOrderConfirmList = Lists.newArrayList();
        String blocked = (String) params.get("blocked");
        List<CustomerOrderPO> list = null;
        if(OrderStateEnum.UN_CONFIRM.getCode().equals(blocked)){
            list = orderService.selectToBeConfirmed();
        }else if(OrderStateEnum.CONFIRMED.getCode().equals(blocked)){
            list = orderService.selectConfirmed();
        }else{
            list = orderService.selectAll();
        }

        HashMap<String,Object> param = Maps.newHashMap();
        if(list!=null&&!list.isEmpty()){
            list.forEach(e->{
                HashMap<String, Object> orderConfirm = Maps.newHashMap();
                orderConfirm.put("orderNo",e.getF1927());
                orderConfirm.put("start", OrderStateEnum.getValueByCode(e.getBlocked()==null?"0":e.getBlocked()));

                List<CustomerOrderItemPO>  orderItem= e.getOrderItems();
                if(orderItem!=null&&orderItem.size()>0){
                    CustomerOrderItemPO customerOrderItemPO = orderItem.get(0);
                    param.put("F3125",customerOrderItemPO.getF1947());//商品编号
                    List<GoodsVO> vos = goodsService.selectByBean(this.getUserDefDbName(), param);
                    GoodsVO goodsVO = vos.get(0);
                    orderConfirm.put("list_pic_url", goodsVO.getF8164_picUrl());
                    orderConfirm.put("name",goodsVO.getF3132_name());
                }

                orderConfirm.put("retail_price", e.getTotalAmt());
                orderConfirm.put("order_date", e.getF1931());
                cOrderConfirmList.add(orderConfirm);
                param.clear();
            });
        }

        return toResponsSuccess(cOrderConfirmList);
    }

    /**
     * 客户订单确认列表
     */
    @ApiOperation(value = "客户订单确认列表", response = Map.class)
    @ApiImplicitParams({@ApiImplicitParam(name = "orderNo", value = "订单编号", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping("cOrderConfirm")
    public Object cOrderConfirm(String orderNo) {

        CustomerOrderPO orderPO = orderService.selectByOrderNo(orderNo);
        HashMap<String, Object> orderConfirm = getOrderData(orderPO);
        return toResponsSuccess(orderConfirm);
    }


    /**
     * 用户订单确认取消操作
     */
    @ApiOperation(value = "客户订单确认取消操作", response = Map.class)
    @ApiImplicitParams({@ApiImplicitParam(name = "orderNo", value = "订单编号", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping("cOrderGoCancel")
    public Object cOrderGoCancel(String orderNo) {
        CustomerOrderPO orderPO = orderService.selectByOrderNo(orderNo);
        orderPO.setBlocked(OrderStateEnum.CANCELED.getCode());
        orderPO.setF1931(new Date(System.currentTimeMillis()));
        orderService.saveOrUpdate(orderPO);
        HashMap<String, Object> orderConfirm = getOrderData(orderPO);
        return toResponsSuccess(orderConfirm);
    }

    /**
     * 用户订单确认取消操作
     */
    @ApiOperation(value = "客户订单确认取消操作", response = Map.class)
    @ApiImplicitParams({@ApiImplicitParam(name = "orderNo", value = "订单编号", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping("cOrderGoConfirm")
    public Object cOrderGoConfirm(String orderNo) {
        CustomerOrderPO orderPO = orderService.selectByOrderNo(orderNo);
        orderPO.setBlocked(OrderStateEnum.CONFIRMED.getCode());
        orderPO.setF1931(new Date(System.currentTimeMillis()));
        orderService.saveOrUpdate(orderPO);
        HashMap<String, Object> orderConfirm = getOrderData(orderPO);
        return toResponsSuccess(orderConfirm);
    }

    public HashMap<String, Object> getOrderData(CustomerOrderPO orderPO) {

        HashMap<String, Object> orderConfirm = Maps.newHashMap();

        //商品基本信息
        orderConfirm.put("orderNo",orderPO.getF1927());
        orderConfirm.put("start", OrderStateEnum.getValueByCode(orderPO.getBlocked()==null?"0":orderPO.getBlocked()));

        List<CustomerOrderItemPO>  orderItem= orderPO.getOrderItems();
        if(orderItem!=null&&orderItem.size()>0) {
            CustomerOrderItemPO customerOrderItemPO = orderItem.get(0);
            HashMap<String,Object> param = Maps.newHashMap();
            param.put("F3125",customerOrderItemPO.getF1947());//商品编号
            List<GoodsVO> vos = goodsService.selectByBean(this.getUserDefDbName(), param);
            GoodsVO goodsVO = vos.get(0);
            orderConfirm.put("list_pic_url", goodsVO.getF8164_picUrl());
            orderConfirm.put("name",goodsVO.getF3132_name());
            orderConfirm.put("retail_price", orderPO.getTotalAmt());
            orderConfirm.put("order_date", orderPO.getF1931());

            //商品码段信息
            List<HashMap<String, Object>> goodsObjList = Lists.newArrayList();

            orderItem.forEach(e->{
                HashMap<String, Object> goodsObj = Maps.newHashMap();
                goodsObj.put("md", e.getF2116());
                goodsObj.put("md_val", e.getF12694());
                goodsObj.put("goods_colour",e.getF1936());
                goodsObjList.add(goodsObj);
            });

            orderConfirm.put("goodsObjList", goodsObjList);

            //用户信息
            HashMap<String, Object> userObj = Maps.newHashMap();
            userObj.put("name", orderPO.getF1928());
            userObj.put("phone", orderPO.getF1952());
            orderConfirm.put("userObj", userObj);
        }

        return orderConfirm;
    }

    /**
     * 反馈成功
     *
     * @param data 具体反馈数据
     * @return 反馈结果
     */
    public static Map<String, Object> toResponsSuccess(Object data) {
        Map<String, Object> rp = ResponseUtils.toResponsObject(0, "执行成功", data);
        //log.info("response:" + rp);
        return rp;
    }

    /**
     * 货品上架
     */
    @ApiOperation(value = "货品上架界面")
    @ApiImplicitParams({@ApiImplicitParam(name = "goodsId", value = "商品ID", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping("cGoodsShelves")
    public Object cGoodsShelves(String goodsId) {

        Map param =  Maps.newHashMap();
        param.put("f3125",goodsId);
        List<GoodsVO> vos = goodsService.selectByBean(getUserDefDbName() , param);

        HashMap<String, Object> goods = Maps.newHashMap();
        if(!BeanUtils.isNull(vos)){

            GoodsVO goodsVO = vos.get(0);

            //商品基础信息
            goods.put("goods_id", goodsId);
            goods.put("shelves_start",  goodsVO.getF8500_status());
            goods.put("name", goodsVO.getF3132_name());
            goods.put("retail_price", goodsVO.getF3131_price());
            //goods.put("create_date", "2020-07-17 16:47:52");


            //商品图片
            List<HashMap<String, Object>> goodsImgList = Lists.newArrayList();

            Arrays.stream(goodsVO.getPicUrls()).forEach(e->{
                HashMap<String, Object> goodsImg = Maps.newHashMap();
                goodsImg.put("image_url", e);
                goodsImgList.add(goodsImg);
            });

            //商品码段信息
            List<HashMap<String, Object>> goodsObjList = Lists.newArrayList();
            HashMap<String, Object> goodsObj = Maps.newHashMap();
            goodsObj.put("md",goodsVO.getF3129_size() );
            goodsObj.put("goods_colour", goodsVO.getF3128_color());
            goodsObjList.add(goodsObj);

            goods.put("imgList", goodsImgList);
            goods.put("goodsObjList", goodsObjList);
        }
        return toResponsSuccess(goods);
    }


    /**
     * 货品上架
     */
    @ApiOperation(value = "上传图片更新")
    @ApiImplicitParams({@ApiImplicitParam(name = "goodsId", value = "商品ID", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping("cGoodsShelvesUploadImg")
    public Object cGoodsShelvesUploadImg(String goodsId) {
        Map param =  Maps.newHashMap();
        param.put("f3125",goodsId);
        List<GoodsVO> vos = goodsService.selectByBean(getUserDefDbName() , param);
        List<HashMap<String, Object>> goodsImgList = Lists.newArrayList();
        if(!BeanUtils.isNull(vos)){
            GoodsVO goodsVO = vos.get(0);
            //商品图片
            Arrays.stream(goodsVO.getF8164_picUrl().split(",")).forEach(e->{
                HashMap<String, Object> goodsImg = Maps.newHashMap();
                goodsImg.put("image_url", e);
                goodsImgList.add(goodsImg);
            });
        }
        return toResponsSuccess(goodsImgList);
    }

    //获取当前日期时间的string类型用于文件名防重复
    public String dates() {
        Date currentTime = new java.util.Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    @ApiOperation(value = "上传商品图片")
    @ApiImplicitParams({@ApiImplicitParam(name = "goodsId", value = "商品ID", paramType = "path", required = true)})
    @IgnoreAuth
    @RequestMapping("uploadPicture")
    public void uploadPicture(String goodsId, HttpServletRequest request, HttpServletResponse response, PrintWriter writer) throws Exception {

        //获取从前台传过来得图片
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = req.getFile("file");
        //获取图片的文件类型
        String houzhu = multipartFile.getContentType();
        int one = houzhu.lastIndexOf("/");
        //根据获取到的文件类型截取出图片后缀
        String type = houzhu.substring((one + 1), houzhu.length());

        String filename=null;
        String realPath = "D:/upload/";
        try {
            File dir = new java.io.File(realPath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            //获取到当前的日期时间用户生成文件名防止文件名重复
            String filedata = this.dates();
            //生成一个随机数来防止文件名重复
            int x = (int) (Math.random() * 1000);
            filename = "upload" + x + filedata;
            System.out.println(x);
            //将文件的地址和生成的文件名拼在一起
            File file = new File(realPath, filename + "." + type);
            multipartFile.transferTo(file);

            //更新商品表
            String requestUrl = "http://"+request.getServerName()+":"+request.getServerPort()+"/upload/";
            goodsService.updateUrl(this.getUserDefDbName(),goodsId,requestUrl+filename + "." + type);
            //将图片在项目中的地址和isok状态储存为json格式返回给前台
            Map<String, Object> map = Maps.newHashMap();
            map.put("isok", 1);
            map.put("dizhi", "/upload/" + filename + "." + type);
            Object jsonObject = JSONArray.toJSON(map);
            writer.write(jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 货品上架
     */
    @ApiOperation(value = "上架下架")
    @ApiImplicitParams({@ApiImplicitParam(name = "goodsId", value = "商品ID", paramType = "path", required = true),@ApiImplicitParam(name = "onOff", value = "上下架标识", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping("cGoodsShelvesOnOff")
    public Object cGoodsShelvesOnOff(String goodsId,String onOff) {
        goodsService.updateStatus(this.getUserDefDbName(),goodsId,onOff);
        return toResponsSuccess(null);
    }
}
